<template>
  <view 
    class="calendar-container"
    @longpress="handleLongPress"
    :style="bgImageStyle"
  >
    <!-- 半透明遮罩确保文字可读性 -->
    <view class="bg-overlay" v-if="hasBackground"></view>
  
    <!-- 月份导航 -->
    <view class="month-header">
      <view class="nav-btn" @click="prevMonth">
        <uni-icons type="arrowleft" size="20" color="#2775b6"></uni-icons>
      </view>
      <picker 
        mode="date" 
        fields="month"
        :value="pickerDate"
        :start="minDate"
        :end="maxDate"
        @change="handleMonthChange"
        class="month-picker"
      >
        <text class="month-title">{{ displayMonth }}</text>
      </picker>
      <view class="nav-btn" @click="nextMonth">
        <uni-icons type="arrowright" size="20" color="#2775b6"></uni-icons>
      </view>
    </view>

    <!-- 星期标题 -->
    <view class="weekdays">
      <view v-for="day in weekdays" :key="day" class="weekday">
        {{ day }}
      </view>
    </view>

    <!-- 日期格子 -->
    <view class="days-grid">
      <view 
        v-for="(day, index) in calendarDays" 
        :key="index"
        class="day-cell"
        :class="{
          'current-month': day.isCurrentMonth,
          'today': day.isToday,
          'selected': day.isSelected,
          'has-log': day.hasLog
        }"
        @click="selectDate(day.date)"
      >
        <text class="day-number">{{ day.day }}</text>
        <view v-if="day.hasLog" class="log-indicator"></view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useHomeStore } from '@/stores/homeStore'

const homeStore = useHomeStore()
const weekdays = ['日', '一', '二', '三', '四', '五', '六']
const currentDate = ref(new Date())
const pickerDate = ref('')
const minDate = ref('2000-01')
const maxDate = ref('2030-12')

// 背景图使用store中的状态
// 修改后的 computed 属性
const bgImage = computed(() => {
  return homeStore.calendarBgImage?.startsWith('_www/') 
    ? homeStore.calendarBgImage.replace('_www/', '') 
    : homeStore.calendarBgImage
})

const hasBackground = computed(() => bgImage.value !== null)

// 背景图样式
const bgImageStyle = computed(() => {
  return bgImage.value 
    ? { backgroundImage: `url(${bgImage.value})` } 
    : {}
})

// 计算显示的月份文本
const displayMonth = computed(() => {
  return `${currentDate.value.getFullYear()}年${currentDate.value.getMonth() + 1}月`
})

// 计算当月天数
const daysInMonth = computed(() => {
  return new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() + 1,
    0
  ).getDate()
})

// 计算当月第一天是星期几
const firstDayOfMonth = computed(() => {
  return new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth(),
    1
  ).getDay()
})

// 计算上个月的天数
const prevMonthDaysCount = computed(() => {
  return new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth(),
    0
  ).getDate()
})

// 生成日历数组（已修复日期计算问题）
const calendarDays = computed(() => {
  const days = []
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const todayStr = formatDate(today)
  const selectedDateStr = formatDate(new Date(homeStore.selectedDate))
  const currentYear = currentDate.value.getFullYear()
  const currentMonth = currentDate.value.getMonth()

  // 上个月末尾几天（修复：只显示实际需要的天数）
  const prevMonthDays = firstDayOfMonth.value
  for (let i = prevMonthDays - 1; i >= 0; i--) {
    const prevDate = new Date(currentYear, currentMonth - 1, prevMonthDaysCount.value - i)
    days.push(createDayObject(prevDate, false, todayStr, selectedDateStr))
  }

  // 当月所有天
  for (let i = 1; i <= daysInMonth.value; i++) {
    const date = new Date(currentYear, currentMonth, i)
    days.push(createDayObject(date, true, todayStr, selectedDateStr))
  }

  // 下个月开头几天（修复：从1号开始正确计算）
  const nextMonthDays = 42 - days.length // 6行x7天
  for (let i = 1; i <= nextMonthDays; i++) {
    const date = new Date(currentYear, currentMonth + 1, i)
    days.push(createDayObject(date, false, todayStr, selectedDateStr))
  }

  return days
})

// 格式化日期为YYYY-MM-DD（修复时区问题）
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 创建日期对象（确保今日标记准确）
const createDayObject = (date, isCurrentMonth, todayStr, selectedDateStr) => {
  const dateStr = formatDate(date)

  // 精确比较年月日（修复今日标记问题）
  const isToday = dateStr === todayStr

  return {
    date: dateStr,
    day: date.getDate(),
    isCurrentMonth,
    isToday,
    isSelected: dateStr === selectedDateStr,
    hasLog: homeStore.markedDates.includes(dateStr)
  }
}

// 长按事件处理
// 修改 handleLongPress 方法中的清除背景部分
const handleLongPress = () => {
  uni.showActionSheet({
    itemList: ['更换背景', '清除背景'],
    success: (res) => {
      if (res.tapIndex === 0) {
        chooseImage()
      } else {
        // 修改这里：直接调用 store 的方法清除背景
        homeStore.saveCalendarBgImage(null) // 传入 null 清除背景
		uni.showToast({ title: '背景已清除', icon: 'success' })
      }
    }
  })
}

// 选择图片
// 修改后的 chooseImage 方法
const chooseImage = () => {
  uni.chooseImage({
    success: (res) => {
      homeStore.saveCalendarBgImage(res.tempFilePaths[0])
    }
  })
}

// 选择日期
const selectDate = (date) => {
  homeStore.setSelectedDate(date)
}

// 上个月
const prevMonth = () => {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() - 1,
    1
  )
  updatePickerDate()
}

// 下个月
const nextMonth = () => {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() + 1,
    1
  )
  updatePickerDate()
}

// 处理月份选择
const handleMonthChange = (e) => {
  const [year, month] = e.detail.value.split('-')
  currentDate.value = new Date(year, month - 1, 1)
  homeStore.setSelectedDate(formatDate(currentDate.value))
}

// 更新picker日期值
const updatePickerDate = () => {
  const year = currentDate.value.getFullYear()
  const month = (currentDate.value.getMonth() + 1).toString().padStart(2, '0')
  pickerDate.value = `${year}-${month}`
}

// 初始化picker日期
updatePickerDate()

// 监听月份变化
watch(currentDate, () => {
  updatePickerDate()
})

// 初始化时从store加载背景图
onMounted(() => {
  homeStore.initFromStorage()
})
</script>

<style scoped>
/* 完全保持原始样式不变 */
.calendar-container {
  background-color: white;
  border-radius: 12px;
  padding: 12px;
  margin: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  background-size: cover;
  background-position: center;
  overflow: hidden;
}

.bg-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 0;
}

.month-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  margin-bottom: 12px;
  position: relative;
  z-index: 1;
}

.month-picker {
  flex: 1;
  display: flex;
  justify-content: center;
}

.month-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  padding: 8px 16px;
  position: relative;
  z-index: 1;
  text-shadow: 0 0 2px rgba(255, 255, 255, 0.8);
}

.nav-btn {
  padding: 8px;
  border-radius: 50%;
  position: relative;
  z-index: 1;
}

.nav-btn:active {
  background-color: rgba(135, 206, 235, 0.2);
}

.weekdays {
  display: flex;
  margin-bottom: 8px;
  position: relative;
  z-index: 1;
}

.weekday {
  flex: 1;
  text-align: center;
  font-size: 12px;
  color: #666;
  text-shadow: 0 0 2px rgba(255, 255, 255, 0.8);
}

.days-grid {
  display: flex;
  flex-wrap: wrap;
  position: relative;
  z-index: 1;
}

.day-cell {
  width: calc(100% / 7);
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  border-radius: 8px;
}

.day-number {
  font-size: 14px;
  text-shadow: 0 0 2px rgba(255, 255, 255, 0.8);
  position: relative;
  z-index: 1;
}

.day-cell.current-month .day-number {
  color: #333;
}

.day-cell:not(.current-month) .day-number {
  color: #ccc;
}

.day-cell.today .day-number {
  color: #2775b6;
  font-weight: bold;
}

.day-cell.selected {
  background-color: #87CEEB;
}

.day-cell.selected .day-number {
  color: white;
  text-shadow: none;
}

.log-indicator {
  position: absolute;
  bottom: 4px;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #2775b6;
  z-index: 1;
}
</style>